package com.igoal.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.DataStatus;
import com.igoal.entity.UserGoalDone;
import com.igoal.entity.UserGoalPk;

@Repository("userGoalEntryDoneDAO")
public class UserGoalEntryDoneDAOImpl extends GenericDaoHibernate<UserGoalDone, Long>
		implements UserGoalEntryDoneDAO {

	public UserGoalEntryDoneDAOImpl() {
		super(UserGoalDone.class);
	}

	public List<UserGoalDone> findByFK(Long userId, Long goalId) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalDone.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		
		List<UserGoalDone> result = findByCriteria(dc);		
		return result;
	}

	public List<UserGoalDone> findByFK(UserGoalPk fk) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalDone.class);
		dc.add(Restrictions.eq("userGoal.pk", fk));
		
		List<UserGoalDone> result = findByCriteria(dc);	
		return result;
	}

	public List<UserGoalDone> listDoneEntriesByGoal(Long goalId,
			int numberOfEntries, String orderBy) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalDone.class);
		dc.add(Restrictions.eq("userGoal.pk.goal.id", goalId));
		getByStatus(dc, DataStatus.USING);
		
		if(orderBy != null)
			dc.addOrder(Order.desc(orderBy));
		
		List<UserGoalDone> result; 
		if(numberOfEntries >= 0)
			result = findByCriteria(dc, 0, numberOfEntries);
		else
			result = findByCriteria(dc);
		
		return result;
	}

	public List<UserGoalDone> listDoneEntriesByUser(Long userId,
			int numberOfEntries, String orderBy) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalDone.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		getByStatus(dc, DataStatus.USING);
		
		if(orderBy != null)
			dc.addOrder(Order.desc(orderBy));
		
		List<UserGoalDone> result; 
		if(numberOfEntries >= 0)
			result = findByCriteria(dc, 0, numberOfEntries);
		else
			result = findByCriteria(dc);
		
		return result;
	}

	public int countDoneEntries(Long userId){
		DetachedCriteria dc = DetachedCriteria.forClass(UserGoalDone.class);
		dc.add(Restrictions.eq("userGoal.pk.user.id", userId));
		getByStatus(dc, DataStatus.USING);
				
		return countByCriteria(dc);
	}
	
}
